import {
  getPlayListType,
  getHotSong
} from '../../utils/http'
// const audio = getApp().audio
Page({
  pageNumber: 1,
  typeListId: null, // 类别id。可不填，默认值"index"
  hotSong: [],
  async onLoad() {
    // 获取类别
    wx.showLoading({
      title: '',
      mask: true
    })
    let res = await getPlayListType()
    wx.hideLoading()
    let typeClickIndexArr = []
    res.typeList.map(() => typeClickIndexArr.push(-1))
    this.setData({
      typeList: res.typeList,
      typeClickIndexArr
    })

    // 根据指定类别id，获取歌单
    await this.getSongList()
  },
  // 加载更多
  loadMore() {
    if (this.data.hasMore) {
      this.pageNumber += 1
      this.getSongList()
    }
  },
  // 切换类别
  async changeType(e) {
    let {
      id,
      type,
      name,
      index,
      index2
    } = e.target.dataset
    this.typeListId = id
    this.pageNumber = 1
    this.hotSong = []
    await this.getSongList()
    let typeClickIndexArr = this.data.typeClickIndexArr

    console.log(typeClickIndexArr[index])
    typeClickIndexArr.map((item3, index3) => typeClickIndexArr[index3] = index3 === index ? index2 : -1)
    this.setData({
      typeClickIndexArr
    })
  },
  // 获取内容
  async getSongList() {
    wx.showLoading({
      title: '',
      mask: true
    })
    let res = await getHotSong({
      typeId: this.typeListId,
      pageNumber: this.pageNumber
    })
    wx.hideLoading()
    if (res.code !== 200) {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
    this.hotSong.push(...res.list)
    this.setData({
      hotSong: this.hotSong,
      totalPage: res.totalPage,
      nowPageNumber: res.nowPageNumber,
      hasMore: res.nowPageNumber < res.totalPage
    })
  },
  toHotSongList(e) {
    let {
      id,
      title
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/music/index?id=${id}&navtitle=${title}&type=song`,
    })
  },
  collection(e) {
    let {
      id
    } = e.currentTarget.dataset
    let list = this.data.hotSong.filter(item => item.listId == id)[0]
    let collectionSong = wx.getStorageSync('collectionSong') || []
    // 循环收藏，找出是否收藏过
    let find_i = collectionSong.findIndex(item => item.listId == id)
    if (find_i !== -1) { // 同id的歌曲被收藏过，删除原记录。后续会将数据添加到第一个
      collectionSong.splice(find_i, 1)
    }
    collectionSong.unshift(list)
    wx.setStorage({
      key: "collectionSong",
      data: collectionSong,
      success: () => {
        wx.showToast({
          title: '已加入收藏',
          icon: 'none'
        })
      }
    })
  },
})